using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Soft1ApiDemo.Domain.Entity;
using Soft1ApiDemo.Domain.Repository;
using Microsoft.Extensions.Logging;

namespace Soft1ApiDemo.Infrastructure.Filters
{
    public class CustomGlobalExceptionFilter : IAsyncExceptionFilter
    {
        // private readonly IRepository<AppLog> _appLogRes;
        private readonly IRepository<AppLog> _logger;

        public CustomGlobalExceptionFilter(IRepository<AppLog> logger)
        {
            _logger = logger;
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                string msg = context.Exception.Message;
                // context.Result =
                //     new ContentResult {
                //         Content =
                //             string
                //                 .Format("该错误位于{0},错误内容是:{1}",
                //                 context.ActionDescriptor.ToString(),
                //                 context.Exception.ToString()),
                //         StatusCode = 200,
                //         ContentType = "text/html;charset=utf-8"
                //     };

                //方式二，推荐，获取Startup.cs里面已经注册的实例
                // IWebHost host = Program.BuildWebHost(null);
                // IServiceScope scope = host.Services.CreateScope();
                // ILogRepository _logRepository =
                //     scope.ServiceProvider.GetService<IRepository<AppLog>>();
                // DataContext _dataContext =
                //     scope.ServiceProvider.GetService<Soft1ApiDemoDbContext>();

                    // _logger.Add(new AppLog{
                    //     Message=msg,
                    //     Exception=context.Exception.ToString()
                    // });

                    // _logger.LogError("fffffffffffffff");

                    _logger.Add(new AppLog{
                        Message=msg,
                        Exception=context.Exception.ToString()
                    });

                // ILogRepository logRepository = new LogRepository(dataContext);
                // ILogRepository logRepository = new LogRepository();
                // Log log = new Log();
                // log.Id = Guid.NewGuid();
                // log.RequestURL = url;
                // log.LogTxt = context.Exception.ToString();
                // log.CreateTime = DateTime.Now;
                // _logRepository.Add (log);
                // scope.Dispose();
            }
            context.ExceptionHandled = true; //异常已处理了

            return Task.CompletedTask;
        }
    }
}
